import React, { useEffect, memo, useState } from "react";
import { ScrollView, View } from "@tarojs/components";
import { HomeHeader, HomeSwiper, HomeSearch, HomeHortNews } from "@/components";
import { getHomePage, queryNewList } from "@/services"
import Taro from '@tarojs/taro'


import './index.scss'


const Home = () => {
  const navPosition = Taro.getStorageSync('nav-position') ? JSON.parse(Taro.getStorageSync('nav-position')) : {}
  const [banners, setBanners] = useState([])
  const [newList, setNewList] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    // 如果用户首次进入
    let token = Taro.getStorageSync('auth-token') ?? ''
    if (!token) {
      Taro.reLaunch({
        url: "/login/login/index"
      })
    } else {
      let result1 = getHomePage()
      let result2 = queryNewList({ newsType: 1 })
      Promise.all([result1, result2]).then(([res1, res2]) => {
        res1.data?.banners && setBanners(res1.data.banners)
        if (res2.data) {
          let arr1 = res2.data.filter(item => {
            return item.publishTime && item.publishTime <= new Date().getTime()
          })
          let arr2 = arr1.sort((a, b) => {
            return b.publishTime - a.publishTime
          })
          setNewList(arr2)
        }

      })
    }

  }, [])

  const getNewList = async () => {
    if (loading) { return }
    setLoading(true)
    let result = await queryNewList({ isShowLoading: false, newsType: 1 })
    if (result.data) {
      let arr1 = result.data.filter(item => {
        return item.publishTime && item.publishTime <= new Date().getTime()
      })
      let arr2 = arr1.sort((a, b) => {
        return b.publishTime - a.publishTime
      })
      setNewList(arr2)
    }
    setTimeout(() => {
      setLoading(false)
    }, 1000)

  }

  return (
    <View className='body'>
      <HomeHeader></HomeHeader>
      <View className='emit-box' style={{ padding: `${navPosition.top + 5}px 0 12px` }}>道以星球</View>
      <View className='body-center padding_one' style={{ paddingBottom: '10px', height: `calc(100vh - ${navPosition.top + 25}px)` }}>
        <ScrollView className='scroll-body' refresher-default-style='white' refresherTriggered={loading} scrollY refresherEnabled refresherBackground='#131721' onRefresherRefresh={() => getNewList()}>
          <HomeSwiper banners={banners}></HomeSwiper>
          <HomeSearch></HomeSearch>
          <HomeHortNews newList={newList}></HomeHortNews>
        </ScrollView>

      </View>
    </View>

  );
};

export default memo(Home);
